//
//  MXLockIndicator.m
//  MXLoginMethodsDomo
//
//  Created by 马彦 on 16/9/27.
//  Copyright © 2016年 MX. All rights reserved.
//
/**
 *
 *
 *
 *              密码解锁指示器
 *
 *
 *
 */

#import "MXLockIndicator.h"
#import "MXLockConfig.h"
#import "MXLockCircle.h"

@interface MXLockIndicator ()

@property (nonatomic, strong) NSMutableArray *circleArrayM;
@property (nonatomic, strong) NSMutableArray *selectedCircleArrayM;

@property (nonatomic, assign) CGFloat circleMargin;

@end

@implementation MXLockIndicator

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
        [self initCircles];
    }
    return self;
}

- (void)setup {
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = YES;
    
    self.circleArrayM = [NSMutableArray array];
    self.selectedCircleArrayM = [NSMutableArray array];
    self.circleMargin = MXLOCOR_INDICATOR_SIDE_LENGTH / 15;
}

- (void)initCircles {
    for (int i = 0; i < 9; i++) {
        float x = self.circleMargin * (4.5 * (i % 3) + 1.5);
        float y = self.circleMargin * (4.5 * (i / 3) + 1.5);
        
        MXLockCircle *circle = [[MXLockCircle alloc] initWithDiameter:self.circleMargin * 3];
        circle.tag = MXLOCK_INDICATOR_LEVEL_BASE + i;
        [circle setFrame:CGRectMake(x, y, self.circleMargin * 3, self.circleMargin * 3)];
        [self.circleArrayM addObject:circle];
        [self addSubview:circle];
    }
}

- (void)showPassword:(NSString *)password {
    [self reset];
    
    NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:password.length];
    for (int i = 0; i < password.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *numberStr = [password substringWithRange:range];
        NSNumber *number = [NSNumber numberWithInt:numberStr.intValue];
        [numbers addObject:number];
        [self.circleArrayM[number.intValue] updateCircleState:MXLockCircleStateFill];
        [self.selectedCircleArrayM addObject:self.circleArrayM[number.intValue]];
    }
    [self setNeedsDisplay];
}

- (void)reset {
    for (MXLockCircle *circle in self.circleArrayM) {
        [circle updateCircleState:MXLockCircleStateNormal];
    }
    [self.selectedCircleArrayM removeAllObjects];
}

#pragma mark - draw

- (void)drawRect:(CGRect)rect {
    if (self.selectedCircleArrayM == 0) {
        return;
    }
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, MXLOCK_INDICATOR_TRACK_WIDTH);
    [MXLOCK_COLOR_NORMAL set];
    
    CGPoint addLines[9];
    int count = 0;
    
    for (MXLockCircle *circle in self.selectedCircleArrayM) {
        CGPoint point = CGPointMake(circle.center.x, circle.center.y);
        addLines[count ++] = point;
    }
    CGContextAddLines(context, addLines, count);
    CGContextStrokePath(context);
}

@end
